import 'package:flutter/material.dart';
import '../core/api_response.dart';
import '../models/user.dart';
import '../models/auth_token.dart';
import '../models/login_request.dart';
import '../repositories/auth_repository.dart';
import '../repositories/auth_repository_factory.dart';

enum AuthState {
  initial,      // 初始状态
  loading,      // 加载中
  authenticated,  // 已认证
  unauthenticated,  // 未认证
  error,        // 错误状态
}

class AuthProvider extends ChangeNotifier {
  final AuthRepository _repository;
  
  AuthState _state = AuthState.initial;
  User? _user;
  AuthToken? _token;
  String? _error;
  bool _isLoading = false;
  bool _rememberMe = false;

  // Getters
  AuthState get state => _state;
  User? get user => _user;
  AuthToken? get token => _token;
  String? get error => _error;
  bool get isLoading => _isLoading;
  bool get rememberMe => _rememberMe;
  bool get isAuthenticated => _state == AuthState.authenticated && _user != null && _token != null;

  AuthProvider({AuthRepository? repository})
      : _repository = repository ?? AuthRepositoryFactory.create() {
    _initializeAuth();
  }

  // 初始化认证状态
  Future<void> _initializeAuth() async {
    print('🔄 [AUTH_PROVIDER] 初始化认证状态...');
    _setLoading(true);
    
    try {
      final isLoggedIn = await _repository.isLoggedIn();
      
      if (isLoggedIn) {
        _user = await _repository.getStoredUser();
        _token = await _repository.getStoredToken();
        
        if (_user != null && _token != null) {
          _setState(AuthState.authenticated);
          print('✅ [AUTH_PROVIDER] 用户已登录: ${_user!.username}');
        } else {
          _setState(AuthState.unauthenticated);
          print('⚠️ [AUTH_PROVIDER] 本地数据不完整，需要重新登录');
        }
      } else {
        _setState(AuthState.unauthenticated);
        print('🔓 [AUTH_PROVIDER] 用户未登录');
      }
    } catch (e) {
      _setError('初始化认证状态失败: $e');
      print('❌ [AUTH_PROVIDER] 初始化失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  // 用户登录
  Future<bool> login(LoginRequest request) async {
    print('🔐 [AUTH_PROVIDER] 开始登录: ${request.username}');
    _setLoading(true);
    _clearError();

    try {
      final response = await _repository.login(request);

      if (response.isSuccess && response.data != null) {
        _user = response.data!.user;
        _token = response.data!.token;
        _rememberMe = request.rememberMe;
        _setState(AuthState.authenticated);
        
        print('✅ [AUTH_PROVIDER] 登录成功: ${_user!.username}');
        return true;
      } else {
        _setError(response.error ?? '登录失败');
        print('❌ [AUTH_PROVIDER] 登录失败: ${response.error}');
        return false;
      }
    } catch (e) {
      _setError('登录过程中发生错误: $e');
      print('💥 [AUTH_PROVIDER] 登录异常: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // 用户注册
  Future<bool> register(RegisterRequest request) async {
    print('📝 [AUTH_PROVIDER] 开始注册: ${request.username}');
    _setLoading(true);
    _clearError();

    try {
      final response = await _repository.register(request);

      if (response.isSuccess && response.data != null) {
        print('✅ [AUTH_PROVIDER] 注册成功: ${response.data!.username}');
        
        // 注册成功后自动登录
        final loginRequest = LoginRequest(
          username: request.username,
          password: request.password,
          rememberMe: true,
        );
        
        return await login(loginRequest);
      } else {
        _setError(response.error ?? '注册失败');
        print('❌ [AUTH_PROVIDER] 注册失败: ${response.error}');
        return false;
      }
    } catch (e) {
      _setError('注册过程中发生错误: $e');
      print('💥 [AUTH_PROVIDER] 注册异常: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // 用户登出
  Future<void> logout() async {
    print('🚪 [AUTH_PROVIDER] 用户登出');
    _setLoading(true);

    try {
      await _repository.logout();
      
      _user = null;
      _token = null;
      _rememberMe = false;
      _setState(AuthState.unauthenticated);
      
      print('✅ [AUTH_PROVIDER] 登出成功');
    } catch (e) {
      print('❌ [AUTH_PROVIDER] 登出过程中发生错误: $e');
      // 即使服务端登出失败，也要清理本地状态
      _user = null;
      _token = null;
      _rememberMe = false;
      _setState(AuthState.unauthenticated);
    } finally {
      _setLoading(false);
    }
  }

  // 忘记密码
  Future<bool> forgotPassword(String email) async {
    print('📧 [AUTH_PROVIDER] 发送找回密码邮件: $email');
    _setLoading(true);
    _clearError();

    try {
      final request = ForgotPasswordRequest(email: email);
      final response = await _repository.forgotPassword(request);

      if (response.isSuccess) {
        print('✅ [AUTH_PROVIDER] 找回密码邮件发送成功');
        return true;
      } else {
        _setError(response.error ?? '发送找回密码邮件失败');
        print('❌ [AUTH_PROVIDER] 发送找回密码邮件失败: ${response.error}');
        return false;
      }
    } catch (e) {
      _setError('发送找回密码邮件过程中发生错误: $e');
      print('💥 [AUTH_PROVIDER] 发送找回密码邮件异常: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // 刷新Token
  Future<bool> refreshToken() async {
    if (_token?.refreshToken == null) {
      print('⚠️ [AUTH_PROVIDER] 没有可用的刷新Token');
      return false;
    }

    print('🔄 [AUTH_PROVIDER] 刷新Token...');
    
    try {
      final response = await _repository.refreshToken(_token!.refreshToken);

      if (response.isSuccess && response.data != null) {
        _token = response.data!;
        print('✅ [AUTH_PROVIDER] Token刷新成功');
        notifyListeners();
        return true;
      } else {
        print('❌ [AUTH_PROVIDER] Token刷新失败: ${response.error}');
        // Token刷新失败，可能需要重新登录
        await logout();
        return false;
      }
    } catch (e) {
      print('💥 [AUTH_PROVIDER] Token刷新异常: $e');
      await logout();
      return false;
    }
  }

  // 检查Token是否需要刷新
  Future<void> checkTokenRefresh() async {
    if (_token?.isExpiringSoon == true) {
      print('⏰ [AUTH_PROVIDER] Token即将过期，尝试刷新...');
      await refreshToken();
    }
  }

  // 获取用户信息
  Future<bool> fetchUserProfile() async {
    if (!isAuthenticated) {
      print('⚠️ [AUTH_PROVIDER] 用户未登录，无法获取用户信息');
      return false;
    }

    print('👤 [AUTH_PROVIDER] 获取用户信息...');
    
    try {
      final response = await _repository.getProfile();

      if (response.isSuccess && response.data != null) {
        _user = response.data!;
        print('✅ [AUTH_PROVIDER] 用户信息获取成功');
        notifyListeners();
        return true;
      } else {
        print('❌ [AUTH_PROVIDER] 获取用户信息失败: ${response.error}');
        return false;
      }
    } catch (e) {
      print('💥 [AUTH_PROVIDER] 获取用户信息异常: $e');
      return false;
    }
  }

  // 更新用户信息
  Future<bool> updateProfile(User updatedUser) async {
    if (!isAuthenticated) {
      print('⚠️ [AUTH_PROVIDER] 用户未登录，无法更新用户信息');
      return false;
    }

    print('✏️ [AUTH_PROVIDER] 更新用户信息...');
    _setLoading(true);
    _clearError();

    try {
      final response = await _repository.updateProfile(updatedUser);

      if (response.isSuccess && response.data != null) {
        _user = response.data!;
        print('✅ [AUTH_PROVIDER] 用户信息更新成功');
        return true;
      } else {
        _setError(response.error ?? '更新用户信息失败');
        print('❌ [AUTH_PROVIDER] 更新用户信息失败: ${response.error}');
        return false;
      }
    } catch (e) {
      _setError('更新用户信息过程中发生错误: $e');
      print('💥 [AUTH_PROVIDER] 更新用户信息异常: $e');
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // 清除错误信息
  void clearError() {
    _clearError();
  }

  // 私有方法
  void _setState(AuthState state) {
    _state = state;
    notifyListeners();
  }

  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  void _setError(String error) {
    _error = error;
    _state = AuthState.error;
    notifyListeners();
  }

  void _clearError() {
    _error = null;
    if (_state == AuthState.error) {
      _state = isAuthenticated ? AuthState.authenticated : AuthState.unauthenticated;
    }
    notifyListeners();
  }

  @override
  void dispose() {
    print('🗑️ [AUTH_PROVIDER] AuthProvider disposed');
    super.dispose();
  }
}